<template>
  <el-dialog
    v-model="dialogVisible"
    title="手机号验证"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="phone-verification-container">
      <p class="verification-tip">为了保障您的账户安全，请绑定手机号</p>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="0px">
        <el-form-item prop="phone">
          <el-input 
            v-model="form.phone" 
            placeholder="请输入手机号"
            maxlength="11"
            :disabled="codeSent"
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="code">
          <div class="code-input-container">
            <el-input 
              v-model="form.code" 
              placeholder="请输入验证码"
              maxlength="6"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              :disabled="cooldown > 0 || !form.phone || form.phone.length !== 11" 
              @click="sendCode"
            >
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <div class="button-group">
        <el-button type="primary" @click="verifyCode" :loading="verifying">验证</el-button>
        <el-button type="danger" @click="logout">退出登录</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Phone, Key } from '@element-plus/icons-vue'
import axios from 'axios'
import request from '../utils/request'  // 导入封装好的 axios 实例
import { useRouter } from 'vue-router'

const router = useRouter()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['verified', 'update:visible'])

const dialogVisible = ref(props.visible)
const formRef = ref(null)
const cooldown = ref(0)
const codeSent = ref(false)
const verifying = ref(false)
let timer = null

const form = reactive({
  phone: '',
  code: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 监听visible属性变化
watch(
  () => props.visible,
  (newValue) => {
    dialogVisible.value = newValue
  }
)

// 监听dialogVisible变化，同步更新父组件的visible属性
watch(
  dialogVisible,
  (newValue) => {
    emit('update:visible', newValue)
  }
)

// 发送验证码
const sendCode = async () => {
  try {
    // 表单验证手机号
    await formRef.value.validateField('phone')
    
    // 先启动倒计时，确保UI立即响应
    startCooldown()
    
    // 发送验证码请求
    const response = await request.post('/users/send-sms-code', {
      phone: form.phone
    })
    console.log('发送验证码响应:', response)
    
    // 根据后端返回状态处理结果
    if (response.status === 200) {
      ElMessage({
        type: 'success',
        message: response.msg || '验证码发送成功，请注意查收'
      })
      codeSent.value = true
    } else {
      // 如果请求失败，停止倒计时
      stopCooldown()
      ElMessage({
        type: 'error',
        message: response.msg || '验证码发送失败'
      })
    }
  } catch (error) {
    // 如果出现异常，停止倒计时
    stopCooldown()
    console.error('发送验证码失败:', error)
    
    // 显示错误信息
    ElMessage({
      type: 'error',
      message: error.response?.data?.msg || '发送验证码失败，请稍后重试'
    })
  }
}

// 验证码倒计时
const startCooldown = () => {
  // 清除可能存在的定时器
  stopCooldown()
  
  // 设置初始倒计时值
  cooldown.value = 60
  
  // 创建新的定时器
  timer = setInterval(() => {
    cooldown.value--
    if (cooldown.value <= 0) {
      stopCooldown()
    }
  }, 1000)
}

// 停止倒计时
const stopCooldown = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 验证手机号
const verifyCode = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    verifying.value = true
    
    // 发送验证请求
    const response = await request.post('/users/verify-phone', {
      phone: form.phone,
      code: form.code
    })
    console.log('验证手机号响应:', response)
    
    if (response.status === 200) {
      ElMessage({
        type: 'success',
        message: response.msg || '手机号验证成功'
      })
      emit('verified', form.phone)
      dialogVisible.value = false
    } else {
      ElMessage({
        type: 'error',
        message: response.msg || '验证失败'
      })
    }
  } catch (error) {
    console.error('验证失败:', error)
    ElMessage({
      type: 'error',
      message: error.response?.data?.msg || '验证失败，请检查验证码是否正确'
    })
  } finally {
    verifying.value = false
  }
}

// 退出登录
const logout = () => {
  ElMessage.warning('您选择了退出登录')
  localStorage.removeItem('token')
  localStorage.removeItem('userId')
  localStorage.removeItem('username')
  localStorage.removeItem('isAdmin')
  router.push('/login')
}

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.phone-verification-container {
  padding: 10px;
}

.verification-tip {
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
}

.code-input-container {
  display: flex;
  gap: 10px;
}

.code-input-container .el-input {
  flex: 1;
}

.button-group {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 